<template>
    <canvas ref="canvas" @click="refreshCaptcha"></canvas>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';

  
  
  const canvas = ref(null);
  const correctCode = ref('');
  const inputCode = ref('');
  const freshTime = ref(null)
  const timeCell = 60000

  defineExpose({
    correctCode
  });
  
  // 生成随机验证码
  const generateCode = () => {
    const chars = 'ABCDEFHJKMNPQRSTUVWXYZ2345678';
    let code = '';
    for (let i = 0; i < 4; i++) {
      code += chars[Math.floor(Math.random() * chars.length)];
    }
    correctCode.value = code;
    return code;
  };
  
  // 绘制验证码到 Canvas
  const drawCaptcha = () => {
    const ctx = canvas.value.getContext('2d');
    ctx.clearRect(0, 0, 120, 30);
    ctx.font = '20px Arial';
    ctx.fillStyle = '#' + Math.floor(Math.random()*16777215).toString(16);
    ctx.fillText(generateCode(), 10, 25);
  };
  
  // 初始化 Canvas
  onMounted(() => {
    canvas.value.width = 120;
    canvas.value.height = 30;
    drawCaptcha();
    console.log("aaaa")
    freshTime.value = setInterval(()=>{
      drawCaptcha()
    },timeCell)
  });
  
  // 点击刷新
  const refreshCaptcha = () => {
    drawCaptcha();
    clearInterval(freshTime.value)
    freshTime.value = setInterval(()=>{
      drawCaptcha()
    },timeCell)
  };

  
  // 验证输入
  const validateCode = () => {
    return inputCode.value.toUpperCase() === correctCode.value;
  };
  </script>